package com.gy.ai.agent.util;

import com.alibaba.fastjson2.JSON;
import com.gy.ai.agent.core.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author LGY
 * Create by 2025/6/16 15:14
 */
@Slf4j
public class SysOkHttpClientUtil {
    private static OkHttpClient.Builder okHttpClientBuilder;

    public static OkHttpClient.Builder getOkHttpClientBuilder() {
        return okHttpClientBuilder;
    }

    public static void setOkHttpClientBuilder(OkHttpClient.Builder okHttpClientBuilder) {
        SysOkHttpClientUtil.okHttpClientBuilder = okHttpClientBuilder;
    }

    public static OkHttpClient buildDefaultClient() {
        if (okHttpClientBuilder != null) {
            return okHttpClientBuilder.build();
        }

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.MINUTES)
                .readTimeout(1, TimeUnit.MINUTES);

        String proxyHost = System.getProperty("https.proxyHost");
        String proxyPort = System.getProperty("https.proxyPort");

        if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) {
            InetSocketAddress inetSocketAddress = new InetSocketAddress(proxyHost.trim(), Integer.parseInt(proxyPort.trim()));
            builder.proxy(new Proxy(Proxy.Type.HTTP, inetSocketAddress));
        }
        return builder.build();
    }

    public static <T extends BaseResponse> T doPost(String url, Map<String, String> headers, String jsonBody, Class<T> tClass) {
        // 发起请求
        OkHttpClient client = SysOkHttpClientUtil.buildDefaultClient();
        Request.Builder requestBuilder = new Request.Builder()
                .url(url);
        headers.forEach(requestBuilder::header);
        Request request = requestBuilder.post(RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8")))
                .build();
        try {
            Response resp = client.newCall(request).execute();
            if (!resp.isSuccessful()) {
                throw new RuntimeException("请求失败：" + resp.message());
            }
            if (resp.body() == null) {
                return null;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(resp.body().byteStream(), StandardCharsets.UTF_8));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            log.info("响应结果：{}", sb.toString());
            return JSON.parseObject(sb.toString(), tClass);
        } catch (Exception e) {
            throw new RuntimeException("发送请求异常", e);
        }
    }
}
